<template>
  <div class="commen-container">
    <h1>学生管理</h1>
    <div class="commen-header">
      <div class="header-block ">
        <el-input
          placeholder="请输入要搜索的学生学号"
          v-model="formData.stu_number" size="10">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-input
          placeholder="请输入要搜索的学生姓名"
          v-model="formData.username" size="10">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button type="primary" size="normal" icon="el-icon-search" @click="handleSearch">
          搜索
        </el-button>
        <el-button size="normal" icon="el-icon-refresh" @click="handleClear">
          重置
        </el-button>
      </div>
      <div>
        <el-button type="danger" size="normal" icon="el-icon-delete-solid">
          批量删除
        </el-button>
        <el-button type="success" size="normal" icon="el-icon-circle-plus" @click="">
          新增
        </el-button>
      </div>
    </div>
    <div v-if="!tableData || tableData.length < 1" class="juzhong">
      <span><i class="el-icon-loading"></i>
      加载中</span>
      <el-divider></el-divider>
    </div>
    <div v-else class="post-table">
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border>
        <el-table-column
          type="selection"
          width="80"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="id"
          label="用户id"
          min-width="100"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="学生姓名"
          min-width="100"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          label="头像"
          min-width="100"
          align="center"
          header-align="center"
        >
          <template slot-scope="scope">
            <el-avatar :size="60"
                       :src="scope.row.img_url"
                       style="margin-bottom: 10px">
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column
          prop="stu_number"
          label="学号"
          min-width="100"
          align="center"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="nickname"
          label="昵称"
          min-width="100"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="phone_num"
          label="注册手机号"
          min-width="120"
          align="center"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="gender"
          label="性别"
          min-width="100"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          prop="create_time"
          label="注册时间"
          min-width="150"
          align="center"
          header-align="center"
        >
        </el-table-column>
        <el-table-column
          label="禁言状态"
          align="center"
          header-align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :type="!scope.row.is_mute? 'success' : 'danger'"
              disable-transitions>{{ !scope.row.is_mute ? '正常' : '禁言中' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center"
                         header-align="center"
                         min-width="150">
          <template slot-scope="scope">
            <div class="juzhong" style="flex-direction: row">
              <el-button size="small" @click="getMuting(scope.row)">禁言</el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-divider></el-divider>
    <div class="juzhong">
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formData.pageNum"
          :page-sizes="[10, 50, 100, 150]"
          :page-size="formData.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <el-dialog @close="btnCancel" title="禁言详情" :visible.sync="isMuteDialog" append-to-body>
      <div class="juzhong">
        <el-radio-group v-model="muteData.is_forever">
          <el-radio :label="1" size="large">永久禁言</el-radio>
          <el-radio :label="0" size="large">
            暂时禁言
          </el-radio>
        </el-radio-group>
        <br>
        <el-date-picker
          v-if="!muteData.is_forever"
          v-model="times"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleTimes"
          align="right">
        </el-date-picker>
        <el-input class="mute_reason"
                  type="textarea"
                  style="width: 400px"
                  placeholder="请写出不通过的理由"
                  v-model="muteData.mute_reason"
                  :rows="8"
                  clearable>
        </el-input>
        <div>审核时间:{{ muteData.create_time }}</div>
        <div style="display: flex">
          <el-button type=" primary" @click="handleMute">提交
          </el-button>
          <el-button type=" primary" @click="handleCancel" :disabled="muteData.mute_id==null">取消禁言
          </el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog @close="editCancel" title="修改学生密码" :visible.sync="isEditDialog" append-to-body>
      <div class="juzhong">
        <el-input
          type="password"
          v-model="editData.newPassword"
          placeholder="请输入新密码"
          style="width: 300px;margin: 20px">
        </el-input>
        <el-input
          type="password"
          v-model="editData.confirmPassword"
          placeholder="请再次输入新密码"
          style="width: 300px;margin: 20px"
          :disabled="!editData.newPassword">
        </el-input>
        <div style="color: red" v-if="editData.newPassword && editData.newPassword!== editData.confirmPassword">
          两次输入的密码不一致，请重新输入！
        </div>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px;">
        <el-button type="primary" @click="handleEditSubmit">提交</el-button>
        <el-button @click="editCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addAndupdateMute, getMute, getStuInfo} from "@/api/user";
import {Message} from "element-ui";

export default {
  name: 'Student',
  data() {
    return {
      total: null,
      tableData: null,
      formData: {
        pageSize: 10,
        pageNum: 1,
        stu_number: null,
        username: null
      },
      isMuteDialog: false,
      muteData: {
        mute_id: null,
        user_id: null,
        start_time: null,
        end_time: null,
        create_time: null,
        is_forever: 0,
        deleted: null,
        mute_reason: null
      },
      pickerOptions: {
        shortcuts: [{
          text: '一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      times: [],
      isEditDialog: false,
      editData: {
        newPassword: '',
        confirmPassword: ''
      }
    }
  },
  methods: {
    ClearMuteData() {
      this.muteData = {is_forever: 0}
      this.times = []
    },
    // 处理时间
    handleTimes(val) {
      if (val && val.length === 2) {
        const formattedTimes = val.map(date => this.formatDate(date));
        this.muteData.start_time = formattedTimes[0];
        this.muteData.end_time = formattedTimes[1];
      } else {
        this.muteData.start_time = null;
        this.muteData.end_time = null;
      }
    },
    // 转换时间格式
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    ClearPage() {
      this.formData = {};
    },
    handleClear() {
      this.ClearPage();
      this.fetchTable();
    },
    handleSizeChange(val) {
      this.formData.pageSize = val;
      this.fetchTable();
    },
    handleCurrentChange(val) {
      this.formData.pageNum = val;
      this.fetchTable();
    },
    async fetchTable() {
      try {
        const rep = await getStuInfo(this.formData);
        this.tableData = rep.items;
        this.total = rep.total;
      } catch (e) {
        console.log(e);
        Message.warning("查询无效！");
      }
    },
    handleSearch() {
      console.log(this.formData);
      this.fetchTable();
    },
    async getMuting(data) {
      this.isMuteDialog = true;
      if (data.is_mute) {
        this.muteData = await getMute(data.id);
        this.times = [
          new Date(this.muteData.start_time), // 转换成 Date 对象
          new Date(this.muteData.end_time),   // 转换成 Date 对象
        ];
      }
      this.muteData.user_id = data.id;
    },
    btnCancel() {
      this.isMuteDialog = false
      this.ClearMuteData()
    },
    handleCancel() {
      this.muteData.deleted = 1;
      this.addAndupdateMute()
    },
    handleMute() {
      console.log(this.muteData)
      this.addAndupdateMute()
    },
    async addAndupdateMute() {
      await addAndupdateMute(this.muteData)

      const index = this.tableData.findIndex(item => item.id === this.muteData.user_id);
      if (index !== -1) {
        // 方法 1A：直接修改对象属性 + $set 触发响应式
        const item = this.tableData[index]
        item.is_mute = !this.muteData.deleted
        this.$set(this.tableData, index, item); // 确保 Vue 检测到变化
      }
      Message.success("审核成功！")
      this.btnCancel()
    },
    handleEdit(row) {
      this.isEditDialog = true;
      this.editData = {
        newPassword: '',
        confirmPassword: ''
      };
      this.editData.userId = row.id;
    },
    editCancel() {
      this.isEditDialog = false;
      this.editData = {
        newPassword: '',
        confirmPassword: ''
      };
    },
    handleEditSubmit() {
      if (this.editData.newPassword === this.editData.confirmPassword) {
        // 这里需要调用修改密码的接口，假设接口名为 updatePassword，参数为用户 ID 和新密码
        // 目前只是简单打印信息，实际开发中需要实现接口调用
        console.log(`要修改用户 ${this.editData.userId} 的密码为 ${this.editData.newPassword}`);
        this.isEditDialog = false;
        Message.success("密码修改成功！");
      } else {
        Message.warning("两次输入的密码不一致，请重新输入！");
      }
    }
  },
  mounted() {
    this.fetchTable()
  }
}
</script>

<style scoped>
.mute_reason {
  margin: 5px 0;
}
</style>
